package com.mujin.keji.collectionsystem.module.tripplan.views;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.listeners.CustomItemClickListener;
import com.mujin.keji.collectionsystem.module.tripplan.adapter.StrartAddressAdapter;
import com.mujin.keji.collectionsystem.net.NetworkUtil;
import com.mujin.keji.collectionsystem.permissions.PermissionUtils;
import com.mujin.keji.collectionsystem.permissions.PermissionsObserver;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 输入起点规划路线
 *
 * @author weishixiong
 * @Time 2018-05-16
 */

public class StartTripActivity extends BaseActivity implements BDLocationListener, CustomItemClickListener {
    private MapView bmapView;
    //地图对象
    private BaiduMap baiduMap;
    private EditText etSearch;
    private RecyclerView rvAddress;
    private List<SuggestionResult.SuggestionInfo> suggestionInfoList;
    private LinearLayoutManager linearLayoutManager;
    private StrartAddressAdapter strartAddressAdapter;
    //热词搜索
    private SuggestionSearch mSuggestionSearch;
    private GeoCoder geoCoder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.getInstance().mLocationClient.stop();
        CcsApplication.getInstance().mLocationClient.unRegisterLocationListener(this);
        CcsApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_starttrip;
    }

    @Override
    public void initView() {
        setCenterTitle("选择地点", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        etSearch = (EditText) findViewById(R.id.et_search);
        rvAddress = (RecyclerView) findViewById(R.id.rv_address);
        bmapView = (MapView) findViewById(R.id.bmapView);
        linearLayoutManager = new LinearLayoutManager(this);
        rvAddress.setLayoutManager(linearLayoutManager);
        suggestionInfoList = new ArrayList<>();
        baiduMap = bmapView.getMap();
        mSuggestionSearch = SuggestionSearch.newInstance();
        geoCoder = GeoCoder.newInstance();
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(18.0f);//这里设置了缩放的比例，float类型。
        baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));


    }

    @Override
    public void initData() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        //打开位置设置界面
        getLocationSetting();
        //获取相关权限
        getPermission();
    }

    /**
     * 打开位置设置
     */
    private void getLocationSetting() {
        if (!NetworkUtil.isGpsOPen(this)) {
            CcsApplication.getInstance().mLocationClient.stop();
            //位置信息没有开启
            DialogUtils.showAdressInfoDailog("无法获取当前位置信息，请在手机设置中开启位置信息", StartTripActivity.this);
            //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            //startActivity(intent);

            return;
        }
    }

    /**
     * 获取定位经纬度
     */
    private void getPermission() {
        RxPermissions.getInstance(this).request(
                Manifest.permission.RECORD_AUDIO,//录音权限
                Manifest.permission.ACCESS_COARSE_LOCATION, //定位权限
                Manifest.permission.ACCESS_FINE_LOCATION,//定位权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写权限
                Manifest.permission.READ_EXTERNAL_STORAGE, //读权限
                Manifest.permission.READ_PHONE_STATE,//电话权限
                Manifest.permission.CAMERA//相机权限
        ).
                subscribe(new PermissionsObserver() {
                    @Override
                    protected void onGetPermissionsSuccess() {
                        //开启定位
                        CcsApplication.getInstance().mLocationClient.start();
                        CcsApplication.getInstance().mLocationClient.registerLocationListener(StartTripActivity.this);
                    }

                    @Override
                    protected void onGetPermissionsSuccessFailuer() {
                        if (!PermissionUtils.hasPermission(StartTripActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION})) {
                            DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, StartTripActivity.this);
                            return;
                        }
                        if (!PermissionUtils.hasPermission(StartTripActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
                            DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, StartTripActivity.this);
                            return;
                        }

                        if (!PermissionUtils.hasPermission(StartTripActivity.this, new String[]{Manifest.permission.CAMERA})) {
                            DialogUtils.showPerMissionDailog(Constant.FINALVALUE.CAMERA_MESSAGE, StartTripActivity.this);
                            return;
                        }
                        if (!PermissionUtils.hasPermission(StartTripActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
                            DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, StartTripActivity.this);
                            return;
                        }
                        if (!PermissionUtils.hasPermission(StartTripActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE})) {
                            DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, StartTripActivity.this);
                            return;
                        }
                        if (!PermissionUtils.hasPermission(StartTripActivity.this, new String[]{Manifest.permission.RECORD_AUDIO})) {
                            DialogUtils.showPerMissionDailog(Constant.FINALVALUE.RECORD_MESSAGE, StartTripActivity.this);
                            return;
                        }
                        if (!PermissionUtils.hasPermission(StartTripActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE})) {
                            DialogUtils.showPerMissionDailog(Constant.FINALVALUE.PHONE_MESSAGE, StartTripActivity.this);
                            return;
                        }
                    }
                });
    }

    /**
     * 实时搜索监听器
     */

    OnGetSuggestionResultListener listener = new OnGetSuggestionResultListener() {
        public void onGetSuggestionResult(SuggestionResult res) {

            //获取在线建议检索结果
            if (EmptyUtils.isNotEmpty(res.getAllSuggestions())) {
                suggestionInfoList.clear();
                suggestionInfoList.addAll(res.getAllSuggestions());
                filter();
                if (EmptyUtils.isNotEmpty(suggestionInfoList)) {
                    reflushListView();
                } else {
                    rvAddress.setVisibility(View.GONE);

                }
            } else {
                rvAddress.setVisibility(View.GONE);

            }
        }
    };

    /***
     *递归遍历
     */
    private void filter() {
        if (EmptyUtils.isNotEmpty(suggestionInfoList)) {
            for (int i = 0; i < suggestionInfoList.size(); i++) {
                if (
                        (
                                (!EmptyUtils.isNotEmpty(suggestionInfoList.get(i).pt)))
                                ||
                                (!EmptyUtils.isNotEmpty(suggestionInfoList.get(i).city))
                                ||
                                (!(suggestionInfoList.get(i).city.equals(currentCity)))
                        ) {
                    suggestionInfoList.remove(i);
                    filter();
                }

            }

        }

    }
    private int[] icons = new int[]{
            R.drawable.image_my_location,
         };
    /**
     * 在地图上展示各个点
     *
     * @param pointList
     */
    private void showPointsInBaiduMap(List<LatLng> pointList) {
        //创建OverlayOptions的集合
        List<OverlayOptions> options = new ArrayList<>();
        for (int i = 0; i < pointList.size(); i++) {
            //构建MarkerOption，用于在地图上添加Marker
            MarkerOptions option = new MarkerOptions();
            option.position(pointList.get(i));
            if (i < icons.length) {
                //构建Marker图标
                option.icon(BitmapDescriptorFactory
                        .fromResource(icons[i]));
            } else {
                option.icon(BitmapDescriptorFactory
                        .fromResource(icons[icons.length - 1]));
            }
            //在地图上添加Marker，并显示
            options.add(option);
            //定义文字所显示的坐标点

        }
        //在地图上批量添加
        baiduMap.addOverlays(options);


    }
    private void reflushListView() {
        if (TextUtils.isEmpty(etSearch.toString())) {
            rvAddress.setVisibility(View.GONE);
            return;
        }
        getLoadingDialog().dismiss();
        rvAddress.setVisibility(View.VISIBLE);
        strartAddressAdapter = new StrartAddressAdapter(this, suggestionInfoList, this);
        rvAddress.setAdapter(strartAddressAdapter);
    }

    @Override
    public void initListener() {
        mSuggestionSearch.setOnGetSuggestionResultListener(listener);
        RxTextView.textChanges(etSearch)
                //监听输入完1秒之后发送事件
                .debounce(500, TimeUnit.MILLISECONDS)
                //跳过输入框EditText 初始化的的时候产生的事件。
                .skip(1)
                //把观察者切换到UI线程
                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new rx.Observer<CharSequence>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(CharSequence charSequence) {
                        if (TextUtils.isEmpty(charSequence.toString())) {
                           rvAddress.setVisibility(View.GONE);
//                            mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
//                                    .keyword(keyWord)
//                                    .city(currentCity));
                            return;
                        }
                        if (TextUtils.isEmpty(currentCity)) {
                            ToastUtils.showToast("获取当前位置失败，请在设置中检查定位权限或者位置信息是否开启");
                            return;
                        }
                        final String str = charSequence.toString();
                        mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                                .keyword(str)
                                .city(currentCity));
                    }
                });
        //出发 地图的实话  因此 列表
//        baiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
//            @Override
//            public void onTouch(MotionEvent motionEvent) {
//                rvAddress.setVisibility(View.GONE);
//            }
//        });


    }
    private  List<LatLng> pointList;
    /**
     * 定位到某个坐标点
     *
     * @param latitude
     * @param longitude
     */
    private void initMapLocation(double latitude, double longitude) {
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(200)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(latitude)
                .longitude(longitude).build();
        // 设置定位数据
        baiduMap.setMyLocationData(locData);
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.image_now_adress);
        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, mCurrentMarker);
        baiduMap.setMyLocationConfiguration(config);
        // 当不需要定位图层时关闭定位图层
        baiduMap.setMyLocationEnabled(false);
        pointList = new ArrayList<>();
        pointList.add(new LatLng(latitude,longitude));
        showPointsInBaiduMap(pointList);
        mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                .location(new LatLng(latitude,longitude))
                .keyword(keyWord)
                .city(currentCity));

    }

    private String currentCity;
    private String keyWord;
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            currentCity = bdLocation.getCity();
            keyWord =  bdLocation.getAddrStr();
            //在地图中定位当前的位置
            initMapLocation(bdLocation.getLatitude(), bdLocation.getLongitude());
            CcsApplication.getInstance().mLocationClient.stop();

        }
    }

    @Override
    public void onItemClick(View view, int position) {
        EventBus.getDefault().post(suggestionInfoList.get(position));
        finish();
    }
}
